import React, {FC, useEffect, useState} from "react";
import {Button, Form, Input, message} from "antd";
import {Link, useNavigate, useSearchParams} from "react-router-dom";
// 导入正则规则
import {reg} from "../utils";
import api from "../api";


const PhoneLogin: FC = () => {
    const [form] = Form.useForm();
    const [, forceUpdate] = useState({});
    // 发送验证码按钮状态
    const [sendCodeState, setSendCodeState] = useState(false);
    // 发送验证码按钮文本
    const [sendCodeText, setsendCodeText] = useState("获取验证码");
    const navigate = useNavigate()
    const [searchParams] = useSearchParams()
    useEffect(() => {
        forceUpdate({});
    }, []);
    const onCode = async () => {
        // 触发手机号字段验证
        try {
            await form.validateFields(["phone"])
        } catch (e) {
            return;
        }
        // 获取手机号
        let phone = form.getFieldValue("phone");
        // 发送验证码
        api.loginsSendCode({phone}).then(res => {
            if (res.code === 200) {
                message.success("验证码发送成功");
            } else {
                message.error(res.msg);
            }
        }).catch((err) => {
            message.error(err.message);
        })
        // 防狂点
        setSendCodeState(true);
        let time = 60
        // 定时器
        let timer: NodeJS.Timeout | undefined;
        // 延时器
        let delayer: NodeJS.Timeout | undefined
        clearInterval(timer as NodeJS.Timeout)
        clearTimeout(delayer as NodeJS.Timeout)
        setsendCodeText(`${time}s`)
        timer = setInterval(() => {
            time--
            setsendCodeText(`${time}s`)
        }, 1000)
        delayer = setTimeout(() => {
            setSendCodeState(false)
            setsendCodeText("获取验证码")
            clearInterval(timer as NodeJS.Timeout)
            clearTimeout(delayer as NodeJS.Timeout)
        }, 60000)
    }

    return (
        <Form form={form} name="horizontal_login" layout="vertical" initialValues={{phone: searchParams.get("phone")}}
              onFinish={(values) => {
                  delete values.confirmPassword;
                  console.log(values);
                  // 登录
                  api.loginPhone(values).then(res => {
                      if (res.code === 200) {
                          message.success("登录成功");
                          // 存储token
                          sessionStorage.setItem("token", res.token)
                          // 跳转到首页
                          navigate('/')
                      } else {
                          message.error(res.msg);
                      }
                  }).catch(err => {
                      message.error(err.message);
                  })
              }}>
            <Form.Item label="手机号" name="phone" rules={[
                {required: true, message: '手机号是必填项'},
                {pattern: reg.phone, message: '请输入正确的手机号'}
            ]}>
                <Input type="tel" placeholder="请输入手机号"/>
            </Form.Item>
            {/* 验证码 */}
            <div style={{display: 'flex', alignItems: "flex-end", justifyContent: "space-between"}}>
                <Form.Item style={{width: "70%"}} label="验证码" name="code" rules={[
                    {required: true, message: '验证码是必填项'},
                    {pattern: reg.code, message: '请输入正确的四位数组验证码'}
                ]}>
                    <Input placeholder="请输入验证码"/>
                </Form.Item>
                <Form.Item style={{width: "25%"}}>
                    <Button style={{width: "100%"}} type="primary" disabled={sendCodeState}
                            onClick={onCode}>{sendCodeText}</Button>
                </Form.Item>
            </div>
            <Form.Item>
                <div style={{display: "flex", justifyContent: "space-between"}}>
                    <Link to="/register">没有密码，去注册</Link>
                    <Link to="/forget">忘记密码，去重置</Link>
                </div>
            </Form.Item>
            <Form.Item>
                <Button block type="primary" htmlType="submit">登录</Button>
            </Form.Item>
            <Form.Item>
                <Button block htmlType="reset">重置</Button>
            </Form.Item>
        </Form>
    );
}

export default PhoneLogin;